-- 游戏页面
module(..., package.seeall)

local timerId

local lastKey

-- 小鸟切换
local birdS = 1
local birdT = page.src.bird
page.birdSrc = birdT[birdS]
function birdFly()
    page.birdSrc = birdT[birdS]
    birdS = birdS + 1
    if birdS > #birdT then birdS = 1 end
end

-- 进入游戏
function enter()
    local flush -- 刷新分数和云
    local death -- 是否死亡
    
    local w, h = page.bird.width, page.bird.height
    local passH     = 100 -- 可以通过的距离
    local stepX     = 10  -- 横向速度
    local birdW     = 20  -- 鸟宽
    local pipeW     = 60  -- 水管宽
    local bird      = h/2 -- 鸟高
    local dt        = 2   -- 加速度
    local birdSpeed = 0   -- 鸟速
    local score     = 0   -- 得分

    page.birdX = w / 2
    page.birdY = h / 2
    page.cloudX = w / 2
    page.birdPassX = 0
    page.birdStopX = 0
    page.birdPassY = passH / 2
    page.gameover = 0

    lastKey = nil

    page.birdScore = "分数:" .. score
    timerId = sys.timerLoopStart(function()
        birdFly()
        -- 若游戏结束, 停止并退出
        if death and bird > h then
            sys.timerStop(timerId)
            return
        end
        if lastKey and not death then
            birdSpeed = -15
            lastKey = nil
        end
        birdSpeed = birdSpeed + dt
        bird = bird + birdSpeed * dt / 2
        if not death then
            -- 移动柱子
            if page.birdPassX <= -pipeW then
                page.birdPassX = w
                page.birdPassY = math.random(0, passH)
                flush = true
            else
                page.birdPassX = page.birdPassX - stepX
                page.cloudX = page.cloudX - stepX
            end
            -- 计算分数, 刷新云
            if page.birdPassX <= pipeW and flush then
                flush = false
                score = score + 1
                page.birdScore = "分数:" .. score
                page.cloudX = w/2
                page.cloudY = math.random(0, h)
                -- 音乐不播了, 卡
                -- tools.music("pass")
            end
            page.birdStopX = page.birdPassX
        end
        -- 如果游戏结束, 弹出 game over
        if (bird > h or bird < 0) and not death then
            death = true
            page.gameover = 255
            tools.music("shot")
        end
        if not (bird > page.birdPassY + birdW and bird < page.birdPassY + h / 2 -
            birdW) and page.birdPassX < w / 2 + birdW and page.birdPassX > pipeW -
            birdW and not death then
            death = true
            page.gameover = 255
            tools.music("shot")
        end
        -- 移动鸟
        page.birdY = bird
    end, 80)
end

-- 退出游戏
function exit()
    if timerId then
        sys.timerStop(timerId)
        timerId = nil
    end
end

-- 按键跳跃
function keyOkShort() lastKey = true end
